package com.pubinfo.passbook.api.controller.auth;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pubinfo.passbook.common.entity.TAutoTask;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.model.constant.TaskStatusEnum;
import com.pubinfo.passbook.common.model.dto.system.PageParamBase;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.api.vat.ForwardVATService;
import com.pubinfo.passbook.common.service.master.TAutoTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "task")
@Api(tags = "定时任务管理")
@Slf4j
public class AutoTaskController {
  @Autowired
  TAutoTaskService autoTaskService;
  @Autowired
  ForwardVATService vatService;
  @PostMapping("list")
  @ApiOperation(value = "通过名称查询列表数据")
  public JsonResult<MyPage<TAutoTask>> listByName(@RequestBody PageParamBase paramBase) {
    IPage<TAutoTask> iPage = autoTaskService.listTSyncLog(paramBase);
    return JsonResult.success(new MyPage(iPage));
  }
  @PostMapping("saveOrUpdate")
  @ApiOperation(value = "修改或者添加任务")
  public JsonResult<Boolean> edit(@RequestBody TAutoTask task) {
    //新增时
    if (!StringUtils.isEmpty(task.getId())) {  //修改时
      if (task.getStatus().equals(TaskStatusEnum.RUNNING.getCode())) {
        throw new ServiceException("修改之前请先停止任务!");
      }
    }
    autoTaskService.saveOrUpdate(task);
    return JsonResult.success(true);
  }
  
  @GetMapping("/changeStatus/{id}")
  @ApiOperation(value = "改变任务状态")
  public JsonResult<Boolean> changeStatus(@PathVariable("id") String id) {
    return vatService.changeStatusTask(id);
  }
  
  /**
   * 立即运行
   */
  
  @GetMapping("/run/{id}")
  @ApiOperation(value = "")
  public JsonResult<String> run(@PathVariable("id") String id) {
    return vatService.runTask(id);
  }
  
  /**
   * 删除
   */
  
  @PostMapping("/removeBatch")
  @ApiOperation(value = "")
  public JsonResult<String> removeBatch(@RequestParam("ids[]") String[] ids) {
    return vatService.removeBatchTask(ids);
  }
}
